package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {
	writeFile()
	readFile()
	scanFile()
	delFile()
}

func writeFile() {
	d1 := []byte("Hello\nGo\n")
	err := ioutil.WriteFile("./dat1", d1, 0644)
	check(err)

	f, err := os.Create("./dat2")
	check(err)

	defer f.Close()

	d2 := []byte{115, 111, 109, 101, 10}

	n2, err := f.Write(d2)

	check(err)
	fmt.Printf("write %d bytes \n", n2)

	n3, err := f.WriteString("writes \n")

	fmt.Printf("write %d bytes\n", n3)

	f.Sync()

	w := bufio.NewWriter(f)

	n4, err := w.WriteString("bufferd\n")

	fmt.Printf("write %d bytes\n", n4)

	w.Flush()
}

func readFile() {
	d1, e := ioutil.ReadFile("./dat1")
	if e != nil {
		fmt.Println(e)
	}
	fmt.Println("file content : \n ", string(d1))

	f, err := os.Open("./dat1")
	if err != nil {
		fmt.Println(e)
	}
	defer f.Close()
	b1 := make([]byte, 5)
	n1, err := f.Read(b1)
	check(err)
	fmt.Printf("%d bytes : %s\n", n1, string(b1))

	o2, err := f.Seek(6, 0)
	check(err)
	b2 := make([]byte, 2)
	n2, err := f.Read(b2)
	check(err)
	fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))

}

func scanFile() {
	dat, e := ioutil.ReadFile("./dat1")
	if e != nil {
		fmt.Println(e)
	}

	scanner := bufio.NewScanner(strings.NewReader(string(dat)))

	for scanner.Scan() {
		ucl := strings.ToUpper(scanner.Text())
		fmt.Println(ucl)
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
}

func delFile() {
	os.Remove("./dat1")
	os.Remove("./dat2")
	fmt.Println("Remove file ./dat1, ./dat2")
}
